package com.qunar.toku.proxy;

import java.util.concurrent.ConcurrentHashMap;

import com.qunar.toku.handler.ResultHandler;
import com.qunar.toku.socket.CSocket;
import com.qunar.toku.socket.SocketPool;

/**
 * 
 * @author zhangwan
 * @email wan.zhang@qunar.com
 * 
 */
public class Future {
	private final CSocket socket;
	private final ConcurrentHashMap<String, ResultHandler> invokeMap;
	private final SocketPool pool;

	public Future(CSocket socket, ConcurrentHashMap<String, ResultHandler> invokeMap, SocketPool pool) {
		this.socket = socket;
		this.invokeMap = invokeMap;
		this.pool = pool;
	}
	
	public CSocket getSocket() {
		return socket;
	}

	private static class Result {
		Object obj;
	}

	final Result ret = new Result();
	private volatile boolean hasNotified = false; // 异步线程是否结束的标志

	public void preinvoke(RequestProtocol protocol) {
		invoke(protocol, new ResultHandler() {
			@Override
			public void processor(Object message) {
				synchronized (ret) {
					try {
						ret.obj = message;
						ret.notify(); // 异步线程结束,唤醒客户端线程
						hasNotified = true;
					} finally {
						if(socket != null) {
							pool.release(socket);
						}
					}
				}
			}
		});
	}

	public Object get() {
		return get(0);
	}

	public Object get(long timeout) {
		synchronized (ret) {
			if (!hasNotified)
				try {
					ret.wait(timeout); // 客户端线程等待一定时间
				} catch (InterruptedException e) {
					throw new IllegalStateException(e);
				}
		}
		return ret.obj;
	}


	private void invoke(RequestProtocol protocol, ResultHandler result) {
		invokeMap.putIfAbsent(protocol.getKey(), result); // 生成一个token发到服务器端
	}

}
